<?php
if (!defined('sugarEntry')) {
    session_start();
    session_destroy();
    header('Location: ../iphone.php');
}
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, 
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3, 
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Function:    sugar-iphone-client for SugarCRM
* Description: Interface to Sugar Soap
* Author:      Editha Kuske - 2008, Richard John Jensen 2009
* Revision:      $Id: db_soap.php 6 2009-12-26 16:59:05Z richardjohnjensen $
********************************************************************************/
require_once('include/nusoap/nusoap.php');

class Sugar_SOAP_Client
{
    var $soapclient;
    var $soap_error;
    var $soap_debug;
    var $soap_server;
    
    
    // ---------------------------------------
    function add_debug($str) {
        $this->soap_debug.= $str."\n";
    }
    // ---------------------------------------
    function initialize() {
        global $config;
        
        $this->soap_error = '';
        $this->soap_debug = '';
        
        $web_prot = 'http://';
        if (isset($GLOBALS['_SERVER']['HTTPS'])) {
            if ($GLOBALS['_SERVER']['HTTPS'] == 'on') {
                $web_prot = 'https://';
            }
        }
        $this->soap_server = dirname($web_prot.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']).'/soap.php';
        if (isset($_POST['soap_server'])) {
            if (trim($_POST['soap_server']) != '') {
                $_SESSION['soap_server'] = $_POST['soap_server'];
            }
        }
        
        if (isset($_SESSION['soap_server'])) {
            if (trim($_SESSION['soap_server']) != '') {
                $this->soap_server = $_SESSION['soap_server'];
            }
        }
        
        $_SESSION['soap_server'] = $this->soap_server;
        $this->add_debug("Soap Server: $this->soap_server");
        app_log('', 0);
        
        $this->soapclient = new nusoapclient($this->soap_server);
        $soap_error = $this->soapclient->getError();
        //??? doesn't recognize missing soap server
        if ($soap_error) {
            return 0;
        }
        
        if ($config['default_charset'] == 'UTF-8') {
            $this->soapclient->decode_utf8 = 0;
        }
        
        return 1;
    }
    
    // ---------------------------------------
    function soap_call($action, $ar_par, $who) {
        global $soapclient, $config;
        
        $print_str = "--->Soap action: $action\nCaller:$who\n";
        
        $soap_result = $this->soapclient->call($action, $ar_par);
        
        
        if (empty($ar_par)) {
            $print_str.= "Parameter: none\n";
        } else {
            if (is_array($ar_par)) {
                $print_str.= "Parameter: \n".print_r($ar_par, TRUE);
            } else {
                $print_str.= "Parameter: $ar_par\n";
            }
        }
        if ($soap_result === false) {
            $print_str.= "SoapResult: false";
            $error = 1;
        } else {
            if (!is_array($soap_result)) {
                $print_str.= "SoapResult: $soap_result";
            } else {
                $print_str.= "SoapResult: ".print_r($soap_result, TRUE);
                if (is_array($soap_result['error'])) {
                    switch ($soap_result['error']['number']) {
						case  0:
							// No Error
							break;
						case 10:
							// Invalid Login
						case 11:
							// Invalid Session Id
						default:
							$error = 1;
							break;
                    }
                }
            }
        }
        
        $this->add_debug($print_str);
        if ($error) {
            $this->soap_error = $print_str;
        }
        
        return $soap_result;
    }
    
    // ------------------------------------------------------
    function authenticate_user($user_name, $user_password) {
        global $config;
                
        $key = '*';
        $key_md5 = substr($config['ldap_key_md5'], 0, 24);
        
        if ($key_md5 == '') {
            $key = $config['ldap_key'];
            $key_md5 = substr(md5($key), 0, 24);
        }
        
        if ($key == '') {
            $pw_ldap = $user_password;
            // empty LDAP key should only be used with ssl encryption https://...
        } else {
            $pw_ldap = bin2hex(mcrypt_cbc(MCRYPT_3DES, $key_md5, $user_password, MCRYPT_ENCRYPT, 'password'));
        }
        
        $pw_sugar = md5($user_password);
        $har['user_auth']['password'] = $pw_sugar;
        
        $har['user_auth']['user_name'] = $user_name;
        $har['user_auth']['version'] = '.01';
        
        $result = $this->soap_call('login', $har, 'LDAP User Authentication');
        if ($result === false) {
            return 0;
        }
        
        $session_id = $result['id'];
        
        if ($session_id == -1) {
            $har['user_auth']['password'] = $pw_ldap;
            $result = $this->soap_call('login', $har, 'Sugar User Authentication');
            if ($result === false) {
                return 0;
            }
            $session_id = $result['id'];
        }
        if ($session_id == -1) {
            return 0;
        } else {
            $user_id = $this->soap_call('get_user_id', $session_id, 'authenticate_user 2');
            if ($user_id === false) {
                return 0;
            }
            if ($user_id == -1) {
                return 0;
            }
            
            $_SESSION['session_id'] = $session_id;
            $_SESSION['authenticated_user_id'] = $user_id;
            $_SESSION['authenticated_user_name'] = $user_name;
            $_SESSION['authenticated_user_h'] = md5($user_password);
        }
        return 1;
    }
    
    // ---------------------------------------
    function get_module_fields($field_list) {
        $first = 1;
        $ar_module_fields = array();
        
        if (!is_array($field_list)) {
            return $ar_module_fields;
        }
        
        foreach($field_list as $key => $fields) {
            $hname = $fields['name'];
            foreach($fields as $fkey => $val) {
                $ar_module_fields[$hname][$fkey] = $val;
            }
        }
        return $ar_module_fields;
    }
    
    function getCurrencies($related_content_field) {
        global $session_id, $config;
        
        $result_count = 99;
        $ar_currencies = array();
        $ar_currencies['-99'] = $config['default_currency_iso4217'];
        while ($result_count > 20) {
            $result = $this->soap_call('get_entry_list', array('session' => $session_id, 
															'module_name' => 'Currencies', 
															'query' => '', 
															'order_by' => 'currencies.'.$related_content_field, 
															'offset' => '', 
															'select_fields' => array(), 
															'max_results' => 20), 
															'getCurrencies');
            
            $ar_values = $this->get_field_values($result);
            if (empty($ar_values)) {
                break;
            }
            
            foreach($ar_values as $key => $field) {
                $hid = $field['id'];
                $ar_currencies[$hid] = $field[$related_content_field];
            }
            
            $result_count = $result['result_count'];
            $offset = $result['next_offset'];
        }
        //print_r($ar_currencies); die();
        return $ar_currencies;
    }
    
    // ------------------------------------------------------
    // Result = Server time - GMT time in hours
    // ------------------------------------------------------
    function gmt_server_offset() {
        $har = array();
        $str_server_time = $this->soap_call('get_server_time', $har, 'authenticate_user 3');
        $str_gmt_time = $this->soap_call('get_gmt_time', $har, 'authenticate_user 4');
        $server_time = strtotime($str_server_time);
        $gmt_time = strtotime($str_gmt_time);
        
        if ($server_time < $gmt_time ) {
            $plus = -1;
            $diff = $gmt_time - $server_time;
        } else {
            $plus = 1;
            $diff = $server_time - $gmt_time;
        }
        $days= intval($diff/86400);
        $diff = $diff % 86400;
        $hours= round($diff/3600);
        
        if ($days > 0) {
            $hours = $hours + ($days * 24);
        }
        
        return $plus * $hours;
    }
    
    // ------------------------------------------------------
    function gmt_server_offset1() {
        $har = array();
        $htime = $this->soap_call('get_server_time', $har, 'authenticate_user 3');
        $server_time = new DateTime($htime);
        $htime = $this->soap_call('get_gmt_time', $har, 'authenticate_user 4');
        $gmt_time = new DateTime($htime);
        
        return round((date_format($server_time, 'U')-date_format($gmt_time, 'U'))/3600);
    }
    
    // ------------------------------------------------------
    function merge2metafields($ar_module_fields, $bean) {
        global $ar_meta_fields, $ar_meta_data;
        
        if (!isset($ar_meta_data[$bean])) {
			$html = <<<__BLOCK__
			iPhone missing for module $bean $bean_table
__BLOCK__;
			echo $html;
            die();
        }
        
        $ar_meta_fields = $ar_meta_data[$bean];
        foreach($ar_meta_fields as $key => $val) {
            $ar_meta_fields[$key]['type'] = $ar_module_fields[$key]['type'];
            if (empty($ar_meta_fields[$key]['label'])) {
                $ar_meta_fields[$key]['label'] = $ar_module_fields[$key]['label'];
            }
            
            if (!empty($ar_module_fields[$key]['options'])) {
                foreach($ar_module_fields[$key]['options'] as $hidx => $option) {
                    $oval = $option['value'];
                    $ar_meta_fields[$key]['options'][$oval] = $option['name'];
                }
            }
        }
        //print_r($ar_meta_fields); die();
    }
    // ------------------------------------------------------
    function getMetaData($ar_bean_descr) {
        global $ar_meta_fields, $session_id;
        
        $bean = $ar_bean_descr['thin_bean'];
        $bean_table = $ar_bean_descr['bean_table'];
        $module_name = $ar_bean_descr['module_name'];
        
        $result = $this->soap_call('get_module_fields', array('session' => $session_id , 'module_name' => $module_name), 'getMetaData');
        
        $ar_module_fields = $this->get_module_fields($result['module_fields']);
        $this->merge2metafields($ar_module_fields, $bean);
        
        return 1;
    }

    // ---------------------------------------
    function get_sugar_values($soap_result) {
        $ar_sugar_field_spec = array();
        $ar_values = $this->get_field_values($soap_result);
        
        if (!empty($ar_values)) {
            foreach($ar_values[0] as $name => $value)
            $ar_sugar_field_spec[$name]['value'] = $value;
        }
        return $ar_sugar_field_spec;
    }
    // ------------------------------------------------------
    function getModuleData($bean_id) {
        global $ar_bean_descr, $ar_meta_fields;
        global $soapclient, $session_id;
        
        if ($bean_id == '0') {
            return 1;
        }
        
        //print_r($ar_bean_descr);
        $bean = $ar_bean_descr['thin_bean'];
        $module_name = $ar_bean_descr['module_name'];
        $retval = 0;
        
        // ---- Get Fieldnames and bean_table from ar_meta_fields ----------
        $field_names = array();
        
        $result = $this->soap_call('get_entry', array('session' => $session_id, 
													'module_name' => $module_name, 
													'id' => $bean_id, 
													'select_fields' => $field_names), 
													'getModuleData');
        
        $ar_module_fields = $this->get_module_fields($result['field_list']);
        $this->merge2metafields($ar_module_fields, $bean);
        
        $ar_data = $this->get_sugar_values($result);
        
        foreach($ar_meta_fields as $key => $val)
        $ar_meta_fields[$key]['value'] = $ar_data[$key]['value'];
        
        if (isset($ar_meta_fields['currency_id'])) {
            $options = $this->getCurrencies($ar_meta_fields['currency_id']['related_content_field']);
            $currency_id = $ar_meta_fields['currency_id']['value'];
            
            if (!isset($options[$currency_id])) {
                $currency_id = '-99';
                $ar_meta_fields['currency_id']['value'] = $currency_id;
            }
            $ar_meta_fields['currency_id']['options'] = $options;
            $ar_meta_fields['currency_id']['type'] = 'enum';
        }
        
        if (isset($ar_meta_fields['assigned_user_id'])) {
            $hval = $ar_meta_fields['assigned_user_id']['value'];
            $hname = $ar_meta_fields['assigned_user_name']['value'];
            $ar_meta_fields['assigned_user_id']['options'] = array($hval => $hname);
        }
        
        return 1;
    }
    // ----------------------------------------------------------------
    function insert_record($ar_bean_descr) {
        global $session_id, $_SESSION, $ar_meta_fields;
        
        //print_r($ar_meta_fields);die();
        $id = $_SESSION['last_inserted_id'];
        $do_insert_again = 0;
        
        $name_value_list = array();
        $insert_list = array();
        $select_fields = array();
        
        $module_name = $ar_bean_descr['module_name'];
        foreach($ar_meta_fields AS $key => $field) {
            if ((!isset($field['value'])) || ($field['fieldtype'] == 'show_only'))
            continue;
            
            switch($field['fieldtype']) {
				case 'time_part':
					break;
					
				case 'duration':
					$name = 'duration_hours';
					$value = $ar_meta_fields['duration_hours']['value'];
					$name_value_list[] = array('name' => $name, 'value' => $value);
					$insert_list[$name] = $value;
					$select_fields[] = $name;
					
					$name = 'duration_minutes';
					$value = $ar_meta_fields['duration_minutes']['value'];
					$name_value_list[] = array('name' => $name, 'value' => $value);
					$insert_list[$name] = $value;
					$select_fields[] = $name;
					
					break;
					
				default:
					$name = $field['fieldname'];
					$value = $field['value'];
					
					$name_value_list[] = array('name' => $name, 'value' => $value);
					$insert_list[$name] = $value;
					
					if ($ar_bean_descr['bean_table'] == $field['bean_table']) {
						$select_fields[] = $name;
					}
					break;
            }
            
        }
        // foreach
        //print_r($name_value_list);
        //print_r($insert_list);
        if (isset($_SESSION['last_inserted_id'])) {
            $result = $this->soap_call('get_entry', array('session' => $session_id, 
														'module_name' => $module_name, 
														'id' => $id, 
														 'select_fields' => $select_fields), 
														 'insert_record');
            $last_inserted_values = $this->get_field_values($result);
            
            $last_inserted_value = $last_inserted_values[0];
            
            foreach($select_fields as $key => $val) {
                if ($insert_list[$val] != $last_inserted_value[$val]) {
                    $html = <<<__BLOCK__
					$val:<br />$insert_list[$val] last_inserted_value:$last_inserted_value[$val]
__BLOCK__;
					echo $html;
                    $do_insert_again = 1;
                    break;
                }
            }
            if (!$do_insert_again) {
                return $id;
            }
            //echo $id."!!!!!!!!!!!!!!!!!!";
        }
        $result = $this->soap_call('set_entry', array('session' => $session_id, 
													'module_name' => $module_name, 
													'name_value_list' =>  $name_value_list), 
													'insert_record 2');
        
        $_SESSION['last_inserted_id'] = $result['id'];
        return $result['id'];
    }
    
    // ----------------------------------------------------------------
    function update_field(&$field, &$bean_id) {
        global $ar_bean_descr, $ar_meta_fields;
        global $session_id, $_POST;
        
        $module_name = $ar_bean_descr['module_name'];
        $name = $field['fieldname'];
        
        switch ($field['type']) {
			case 'currency':
				$value = (int)$field['value'];
				break;
				
			default:
				$value = $field['value'];
				break;
        }
        
        $name_list_value = array(array('name' => 'id', 'value' => $bean_id), 
        array('name' => $name, 'value' => $value)
        );
        $result = $this->soap_call('set_entry', array('session' => $session_id, 
											        'module_name' => $module_name, 
													'name_value_list' =>  $name_list_value), 
													'update_field');
        $field['info'] = 'update ok';
        return 1;
    }
    
    // ------------------------------------------------------
    function getParentName($id, $module) {
        global $session_id;
        
        switch ($module) {
			case 'Contacts':
				$select_fields = array('last_name', 'first_name');
				break;
				
			case 'Accounts':
			case 'Opportunities':
			default:
				$select_fields = array('name');
				break;
        }
        
        $soap_result = $this->soap_call('get_entry', array('session' => $session_id, 
															'module_name' => $module, 
															'id' => $id, 
															'select_fields' => $select_fields), 
															'getParentName');
        
        $values = $this->get_field_values($soap_result);
        if (!empty($values)) {
            $entry_record = $values[0];
            if((!empty($entry_record['last_name'])) && (!empty($entry_record['first_name'])))
            $name = $entry_record['last_name'].', '.$entry_record['first_name'];
            else {
                $name = $entry_record['name'];
            }
        }
        return $name;
    }
    
    // ------------------------------------------------------
    function getUserName($id_user) {
        if ($id_user == 'All') {
            return 'All';
        }
        
        $soap_result = $this->soap_call('get_entry', array('session' => $GLOBALS['_SESSION'][session_id], 
															'module_name' => 'Users', 
															'id' => $id_user, 
															'select_fields' => array('id', 'last_name', 'first_name', 'user_name')), 
															'getUserName');
        
        $values = $this->get_field_values($soap_result);
        
        /*
[id]  => 
[user_name]  => 
[first_name]  => 
[last_name]  => 
*/
        if (!empty($values)) {
            $entry_record = $values[0];
            $entry_record['full_name'] = '';
            if (!empty($entry_record['last_name'])) {
                $entry_record['full_name'] = $entry_record['last_name'];
                if (!empty($entry_record['first_name'])) {
                    $entry_record['full_name'].= ', '.$entry_record['first_name'];
                }
            }
        }
        return $entry_record;
    }
    
    // ---------------------------------------
    function get_users() {
        global $session_id;
               
        $har = array('user_name' => $_SESSION['authenticated_user_name'], 'user_hash' => $_SESSION['authenticated_user_h'], );        
		$user_list = $this->soap_call('user_list', $har, 'get_users');
        
        if (empty($user_list)) {
            return 0;
        }
        
        $ar_users = array();
        $ar_users[0]['val'] = 'All';
        $ar_users[0]['text'] = 'All';
        for ($i=0; $i<count($user_list); $i++) {
            $ar_users[$i+1]['val'] = $user_list[$i]['id'];
            $ar_users[$i+1]['text'] = $user_list[$i]['last_name'].', '.$user_list[$i]['first_name'];
        }
        
        return $ar_users;
    }
    
    
    // ---------------------------------------
    function get_count($ar_bean_descr, $user_id, $search) {
        global $session_id;
        
        $where = $this->get_sel_parts($ar_bean_descr, $user_id, $search, $orderby, $ar_fields);
        $result = $this->soap_call('get_entries_count', array('session' => $session_id, 
															'module_name' => $ar_bean_descr['module_name'], 
															'query' => $where, 
															'deleted' => 0), 
															'get_count');
        
        /*
echo $search."<br />
echo $where;
print_r($result);
*/
        return $result['result_count'];
    }
    
    // ---------------------------------------
    function get_countOfBean($ar_bean_descr, $user_id, $search) {
        global $ar_beans;
        
        $ar_calls_descr = $ar_beans['Calls'];
        $ar_meetings_descr = $ar_beans['Meetings'];
        
        switch ($ar_bean_descr['module_name']) {
			case 'Calendar':
				$ret_calls = $this->get_count($ar_calls_descr, $user_id, $search);
				$ret_meetings = $this->get_count($ar_meetings_descr, $user_id, $search);
				$ret = $ret_calls + $ret_meetings;
				break;
				
			default:
				$ret = $this->get_count($ar_bean_descr, $user_id, $search);
				break;
        }
        
        return $ret;
    }
    
    // ---------------------------------------
    function get_sel_parts($ar_bean_descr, $user_id, $search, &$orderby, &$ar_fields) {
        global $modus;
        
        $tbl = $ar_bean_descr['bean_table'];
        $orderby = '';
        
        $where = '';
        if ($user_id != 'All') {
            $where.= " ($tbl.assigned_user_id ='$user_id') ";
            if ($search != '') {
                $where.= ' AND ';
            }
        }
        
        switch ($ar_bean_descr['module_name']) {
        case 'Opportunities':
            if ($search != '') {
                $where.= " ($tbl.name like '$search')";
            }
            
            $orderby = "$tbl.name asc";
            $ar_fields = array('id', 'name');
            break;
            
        case 'Contacts':
        case 'Leads':
            if ($search != '') {
                $where.= " (($tbl.last_name like '$search') OR ($tbl.first_name like '$search')) ";
            }
            
            $orderby = "$tbl.last_name, $tbl.first_name";
            $ar_fields = array('id', 'last_name', 'first_name');
            break;
            
        case 'Project':
        case 'ProjectTask':
            if ($modus != 'related') {
                if ($search != '') {
                    $where.= " ($tbl.name like '$search') ";
                }
                
                $orderby = "$tbl.name asc";
                $ar_fields = array('id', 'name');
            } else {
                $where.= $search;
            }
            
            break;
            
        case 'Accounts':
            if ($search != '') {
                $where.= " ($tbl.name like '$search') ";
            }
            
            $orderby = "$tbl.name asc";
            $ar_fields = array('id', 'name');
            break;
            
        case 'Calls':
        case 'Meetings':
            if ($search != '') {
                $where.= "($tbl.date_start>='$search')";
            }
            
            $orderby = " $tbl.date_start ASC";
            $ar_fields = array('id', 'name', 'date_start', 'duration_hours', 'duration_minutes');
            break;
            
            default:
            break;
        }
        
        return $where;
    }

    // ---------------------------------------
    function get_field_values($soap_result) {
        //print_r($soap_result);
        $c = 0;
        $first = 1;
        $ar_values = array();
        
        $har = $soap_result['entry_list'];
        //print_r($har);
        if (!is_array($har)) {
            return $ar_values;
        }
        
        foreach($har as $key => $entry_record) {
            $field_list = $entry_record['name_value_list'];
            foreach($field_list as $key => $ar_entry) {
                $hname = $ar_entry['name'];
                $ar_values[$c][$hname] = $ar_entry['value'];
            }
            $c++;
        }
        return $ar_values;
    }
    
    
    // ---------------------------------------
    function set_relationship($module_name, $module_id, $related_module, $related_module_id) {
        global $session_id;
        
        $set_relationship_value = array('module1' => $module_name, 
										'module1_id' => $module_id, 
										'module2' => $related_module, 
										'module2_id' => $related_module_id, 
										);
        
        $result = $this->soap_call('set_relationship', array('session' => $session_id, 
															'set_relationship_value' => $set_relationship_value), 
															'set_relationship');
        
        //print_r($set_relationship_value);
        //print_r($result);
    }
    
    // ---------------------------------------
    function get_field_values_sorted($soap_result) {
        //print_r($soap_result);die();
        $first = 1;
        $ar_values = array();
        
        $har = (array)$soap_result['entry_list'];
        
        foreach($har as $key => $entry_record) {
            $field_list = $entry_record['name_value_list'];
            foreach($field_list as $key => $ar_entry) {
                //print_r($ar_entry);
                $hid = $ar_entry[0]['value'];
                $ar_values[$hid] = $ar_entry[1]['value'];
            }
        }
        return $ar_values;
    }
    
    
    // ---------------------------------------
    function get_project_tasks($module_id) {
        global $session_id;
        
        $result = $this->soap_call('get_entry_list', array('session' => $session_id, 
															'module_name' => 'ProjectTask', 
															'query' => '(project_id=\''.$module_id.'\')', 
															'order_by' => 'date_start', 
															//        'offset' => $start_pos, 
															'select_fields' => array('name', 'id'), 
															//        'max_results' => , 
															'deleted' => 0), 
															'get_list');
        
        $ar_ids = array();
        foreach($result['ids'] as $key => $val)
        $ar_ids[] = $val['id'];
        
        
        $ar_ret = $this->get_field_values($result);
        //die(print_r($ar_ret, true));
        
        $ar_bean = array();
        $prefix = 'M';
        for ($i=0; $i<count($ar_ret); $i++) {
            $idx = (string)$i;
            while (strlen($idx) < 4) {
                $idx = '0'.$idx;
            }
            switch ($related_module) {
            case 'Contacts':
            case 'Accounts':
            case 'Opportunities':
                if ($related_module == 'Contacts') {
                    $name = $ar_ret[$i]['last_name'].', '.$ar_ret[$i]['first_name'];
                } else {
                    $name = $ar_ret[$i]['name'];
                }
                
                $idx = $name.$idx;
                
                $ar_bean[$idx]['id'] = $ar_ret[$i]['id'];
                $ar_bean[$idx]['table'] = $ar_bean_descr['bean_table'];
                $ar_bean[$idx]['name'] = $name;
                break;
                
            case 'Calls':
                $prefix = 'C';
            case 'Meetings':
                $entry = $ar_ret[$i];
                $str_date = $entry['date_start'];
                $idx = $str_date.$idx;
                
                $ar_bean[$idx]['id'] = $entry['id'];
                $ar_bean[$idx]['name'] = $entry['name'];
                $ar_bean[$idx]['bean'] = 'Call';
                $ar_bean[$idx]['table'] = 'calls';
                $ar_bean[$idx]['date_start'] = $str_date;
                $ar_bean[$idx]['day'] = substr($str_date, 0, 10);
                $ar_bean[$idx]['time'] = substr($str_date, 11, 5);
                $ar_bean[$idx]['type'] = "$prefix ".$entry['duration_hours'].':'.$entry['duration_minutes'];
                break;
                
                default:
                break;
            }
        }
        
        ksort($ar_bean);
        
        
        return $ar_bean;
        
    }
    // ---------------------------------------
    function get_related($module_name, $module_id, $related_module) {
        global $session_id;
        
        $result = $this->soap_call('get_relationships', array('session' => $session_id, 
															'module_name' => $module_name, 
															'module_id' => $module_id, 
															'related_module' => $related_module, 
															'related_module_query' => '', 
															'deleted' => 0), 
															'get_related');
        
        $ar_ids = array();
        foreach($result['ids'] as $key => $val)
        $ar_ids[] = $val['id'];
        
        switch ($related_module) {
        case 'Calls':
        case 'Meetings':
            $select_fields = array();
            break;
            
        case 'Contacts':
            $select_fields = array('last_name', 'first_name', 'id');
            break;
            
            default:
            $select_fields = array('name', 'id');
            break;
        }
        
        //print_r($ar_ids);
        $result = $this->soap_call('get_entries', array('session' => $session_id, 
														'module_name' => $related_module, 
														'ids' => $ar_ids, 
														'select_fields' => $select_fields), 
														'get_related 2');
        
        $ar_ret = $this->get_field_values($result);
        //print_r($ar_ret);
        
        $ar_bean = array();
        $prefix = 'M';
        for ($i=0; $i<count($ar_ret); $i++) {
            $idx = (string)$i;
            while (strlen($idx) < 4) {
                $idx = '0'.$idx;
            }
            switch ($related_module) {
            case 'Contacts':
            case 'Accounts':
            case 'Opportunities':
                if ($related_module == 'Contacts') {
                    $name = $ar_ret[$i]['last_name'].', '.$ar_ret[$i]['first_name'];
                } else {
                    $name = $ar_ret[$i]['name'];
                }
                
                $idx = $name.$idx;
                
                $ar_bean[$idx]['id'] = $ar_ret[$i]['id'];
                $ar_bean[$idx]['table'] = $ar_bean_descr['bean_table'];
                $ar_bean[$idx]['name'] = $name;
                break;
                
            case 'Calls':
                $prefix = 'C';
            case 'Meetings':
                $entry = $ar_ret[$i];
                $str_date = $entry['date_start'];
                $idx = $str_date.$idx;
                
                $ar_bean[$idx]['id'] = $entry['id'];
                $ar_bean[$idx]['name'] = $entry['name'];
                $ar_bean[$idx]['bean'] = 'Call';
                $ar_bean[$idx]['table'] = 'calls';
                $ar_bean[$idx]['date_start'] = $str_date;
                $ar_bean[$idx]['day'] = substr($str_date, 0, 10);
                $ar_bean[$idx]['time'] = substr($str_date, 11, 5);
                $ar_bean[$idx]['type'] = "$prefix ".$entry['duration_hours'].':'.$entry['duration_minutes'];
                break;
                
                default:
                break;
            }
        }
        
        ksort($ar_bean);
        
        
        return $ar_bean;
        
    }
    // ---------------------------------------
    function get_list($ar_bean_descr, $user_id, $search, $start_pos=0, $anz=10) {
        global $session_id;
        $where = $this->get_sel_parts($ar_bean_descr, $user_id, $search, $orderby, $ar_fields);
        $module_name = $ar_bean_descr['module_name'];
        
        $result = $this->soap_call('get_entry_list', array('session' => $session_id, 
														'module_name' => $module_name, 
														'query' => $where, 
														'order_by' => $orderby, 
														'offset' => $start_pos, 
														'select_fields' => $ar_fields, 
														'max_results' => $anz, 
														'deleted' => 0), 'get_list');
        
        $ar_ret = $this->get_field_values($result);
        //echo(print_r($ar_ret, true));
        if (($ar_bean_descr['module_name'] == 'Calls')||($ar_bean_descr['module_name'] == 'Meetings')) {
            return $ar_ret;
        }
        
        
        $ar_bean = array();
        for ($i=0; $i<count($ar_ret); $i++) {
            $ar_bean[$i]['id'] = $ar_ret[$i]['id'];
            $ar_bean[$i]['table'] = $ar_bean_descr['bean_table'];
            
            switch ($ar_bean_descr['module_name']) {
            case 'Contacts':
            case 'Leads':
                $ar_bean[$i]['name'] = $ar_ret[$i]['last_name'].', '.$ar_ret[$i]['first_name'];
                break;
                
                //EK projects start
            case 'Accounts':
            case 'Opportunities':
                $ar_bean[$i]['name'] = $ar_ret[$i]['name'];
                break;
                //EK projects end
                
                default:
                //EK projects start
                if (isset($ar_ret[$i]['name'])) {
                    $ar_bean[$i]['name'] = $ar_ret[$i]['name'];
                }
                //EK projects end
                break;
            }
        }
        return $ar_bean;
    }
    
    // ---------------------------------------
    function get_calendar($ar_bean_descr, $user_id, $since, $start_pos, $anz) {
        global $db, $ar_calls_descr, $ar_meetings_descr;
        
        //get_list(ar_calls_descr, $user_id, $since, $start_pos, $anz);";
        //print_r($ar_bean_descr);
        
        $module_name = $ar_bean_descr['module_name'];
        // --- calls ------
        if (($module_name == 'Calls') || ($module_name == 'Calendar')) {
            $ar_calls = $this->get_list($ar_calls_descr, $user_id, $since, $start_pos, $anz);
            
            $i = 0;
            foreach($ar_calls as $key => $entry) {
                $ar_calls[$i]['id'] = $entry['id'];
                $ar_calls[$i]['name'] = $entry['name'];
                $ar_calls[$i]['bean'] = 'Call';
                $ar_calls[$i]['table'] = 'calls';
                $str_date = $entry['date_start'];
                $ar_calls[$i]['date_start'] = $str_date;
                $ar_calls[$i]['day'] = substr($str_date, 0, 10);
                $ar_calls[$i]['time'] = substr($str_date, 11, 5);
                $ar_calls[$i]['type'] = 'C '.$entry['duration_hours'].':'.$entry['duration_minutes'];
                
                $i++;
            }
            if ($module_name == 'Calls') {
                return $ar_calls;
            }
        }
        
        // --- meetings ------
        if (($module_name == 'Meetings') || ($module_name == 'Calendar')) {
            $ar_meetings = $this->get_list($ar_meetings_descr, $user_id, $since, $start_pos, $anz);
            $i = 0;
            foreach($ar_meetings as $key => $entry) {
                $ar_meetings[$i]['id'] = $entry['id'];
                $ar_meetings[$i]['name'] = $entry['name'];
                $ar_meetings[$i]['bean'] = 'Meeting';
                $ar_meetings[$i]['table'] = 'meetings';
                $str_date = $entry['date_start'];
                $ar_meetings[$i]['date_start'] = $str_date;
                $ar_meetings[$i]['day'] = substr($str_date, 0, 10);
                $ar_meetings[$i]['time'] = substr($str_date, 11, 5);
                $ar_meetings[$i]['type'] = 'M '.$entry['duration_hours'].':'.$entry['duration_minutes'];
                $i++;
            }
            if ($module_name == 'Meetings') {
                return $ar_meetings;
            }
        }
        $ar_bean = array();
        $count_calls = 0;
        $count_meetings = 0;
        $count_bean = 0;
        
        // --------------- Sort by day/time ------------
        while (($count_calls < count($ar_calls)) && ($count_meetings < count($ar_meetings))) {
            if ($ar_calls[$count_calls]['date_start'] < $ar_meetings[$count_meetings]['date_start']) {
                $ar_bean[$count_bean] = $ar_calls[$count_calls];
                $count_calls++;
            } else if ($ar_calls[$count_calls]['date_start'] == $ar_meetings[$count_meetings]['date_start']) {
                $ar_bean[$count_bean] = $ar_calls[$count_calls];
                $count_bean++;
                $ar_bean[$count_bean] = $ar_meetings[$count_meetings];
                $count_calls++;
                $count_meetings++;
            } else if ($ar_calls[$count_calls]['date_start'] > $ar_meetings[$count_meetings]['date_start']) {
                $ar_bean[$count_bean] = $ar_meetings[$count_meetings];
                $count_meetings++;
            }
            $count_bean++;
        }
        while ($count_calls < count($ar_calls)) {
            $ar_bean[$count_bean] = $ar_calls[$count_calls];
            $count_calls++;
            $count_bean++;
        }
        while ($count_meetings < count($ar_meetings)) {
            $ar_bean[$count_bean] = $ar_meetings[$count_meetings];
            $count_meetings++;
            $count_bean++;
        }
        //print_r($ar_bean);
        return $ar_bean;
    }
}
?>